package com.hsgene.message.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.message.constant.SMSErrorCode;
import com.hsgene.message.domain.PushInfo;
import com.hsgene.message.service.NotificationPushService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 系统消息+极光推送
 *
 * @author wxf
 * @date 2018/10/25 14:03
 **/
@RestController
@RequestMapping("/v1.0/genetic/testing/notification")
public class NotificationPushController {

    /**
     * Log
     */
    private final static Logger LOGGER = LogManager.getLogger(NotificationPushController.class);

    @Resource
    private NotificationPushService pushService;

    /**
     * 系统消息+极光推送
     *
     * @param pushInfo 消息内容
     * @param userId   用户id
     * @param isPush   是否使用极光推送(是true，否false)
     * @return
     */
    @PostMapping
    public ApiResult<String> pushNotification(@RequestBody PushInfo pushInfo, String userId, Boolean isPush) {
        try {
            if (pushInfo == null) {
                return ApiResult.fail(SMSErrorCode.PUSH_INFO_IS_NOT_NULL);
            }
            if (StringUtils.isEmpty(userId)) {
                return ApiResult.fail(SMSErrorCode.USER_INFO_IS_NOT_NULL);
            }
            String result = pushService.pushNotification(pushInfo, userId, isPush);
            JSONObject json = JSONObject.parseObject(result);
            return new ApiResult((int) json.get("status"), String.valueOf(json.get("success")),
                    (String) json.get("message"), json.get("timestamp"));
        } catch (Exception e) {
            LOGGER.error("send push is error", e);
            return ApiResult.fail(SMSErrorCode.PUSH_INFO_IS_ERROR);
        }
    }
}
